package com.fxhy.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Date;
import java.util.Random;

import org.springframework.web.multipart.MultipartFile;

import com.baby.contants.CosConstant;
import com.baby.myutils.DateUtils;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;

/**
 * 腾讯云 云对象存储
 * @author lifengyao
 *
 */
public class CosUtil {

	public CosUtil(){
		
	}
	
	/**
	 * 图片路径fileUrl 上传图片
	 * @param fileUrl 本地图片路径
	 * @param cosFileName cos文件夹
	 * @return
	 * @throws URISyntaxException
	 * @throws IOException
	 */
	public static String putFile(String fileUrl,String cosFileName) throws URISyntaxException, IOException{
		// 1 初始化用户身份信息(secretId, secretKey)
		COSCredentials cred = new BasicCOSCredentials(CosConstant.SECRETID, CosConstant.SECRETEKEY);
		 
		// 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
		ClientConfig clientConfig = new ClientConfig(new Region("ap-guangzhou"));
		 
		// 3 生成cos客户端
		COSClient cosClient = new COSClient(cred, clientConfig);
		 
		// bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
		String bucketName = CosConstant.BUCKET;
		 
		File file = new File(fileUrl);
		String nameKey = file.getName(); 
		String prefix=DateUtils.getNowDate() + nameKey.substring(0,nameKey.lastIndexOf("."));
		
		// 对象键（Key）是对象在存储桶中的唯一标识。例如，在对象的访问域名 `bucket1-1250000000.cos.ap-guangzhou.myqcloud.com/doc1/pic1.jpg` 中，对象键为 doc1/pic1.jpg, 
		String key = cosFileName+"/"+ prefix + ".jpg";
		
		PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
		cosClient.putObject(putObjectRequest);
		cosClient.shutdown();
		
		Date expiration = new Date(new Date().getTime() + 5 * 60 * 10000);
		URL url = cosClient.generatePresignedUrl(bucketName, key, expiration);
		
		String newfile = url.toString();
		String urlStr = newfile.substring(0, newfile.indexOf(".jpg?"));
		
		return urlStr+".jpg";
	}
	
	/** 
     * 上传到COS服务器 如果同名文件会覆盖服务器上的 
     * @param instream 
     * @param fileName   文件名称 包括后缀名 
     * @return 出错返回"" ,唯一MD5数字签名 
     */  
    @SuppressWarnings("unused")
	public static String uploadFile2Cos(InputStream instream, String fileName) { 
    	// 1 初始化用户身份信息(secretId, secretKey)
		COSCredentials cred = new BasicCOSCredentials(CosConstant.SECRETID, CosConstant.SECRETEKEY);
		// 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
		ClientConfig clientConfig = new ClientConfig(new Region("ap-guangzhou"));
		// 3 生成cos客户端
		COSClient cosClient = new COSClient(cred, clientConfig);
		// bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
		String bucketName = CosConstant.BUCKET;
    	
        String urlStr = "";
        try {  
            // 创建上传Object的Metadata  
            ObjectMetadata objectMetadata = new ObjectMetadata();  
            objectMetadata.setContentLength(instream.available());  
            objectMetadata.setCacheControl("no-cache");  
            objectMetadata.setHeader("Pragma", "no-cache");  
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));  
            objectMetadata.setContentDisposition("inline;filename=" + fileName);  
            // 上传文件  
            PutObjectResult putResult = cosClient.putObject(bucketName,  fileName, instream, objectMetadata); 
    		Date expiration = new Date(new Date().getTime() + 5 * 60 * 10000);
    		URL url = cosClient.generatePresignedUrl(bucketName, fileName, expiration);
    		
    		String newfile = url.toString();
    		urlStr = newfile.substring(0, newfile.indexOf("?"));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {  
            try {  
                if (instream != null) {  
                    instream.close();  
                }  
            } catch (IOException e) {
                e.printStackTrace();  
            }  
        }
        return urlStr; 
    }   
	
    /**
     * MultipartFile 上传图片
     * @param file
     * @param cosFileName
     * @return
     * @throws Exception
     */
	public static String uploadFile2Cos(MultipartFile file ,String cosFileName) throws Exception {          if (file.getSize() > 10 * 1024 * 1024) {  
            throw new Exception("上传图片大小不能超过10M！");  
        }  
        //图片名称
        String originalFilename = file.getOriginalFilename();  
        //图片后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();  
        //String substring = ".jpg";
        Random random = new Random();  
        //生成新的图片名称(随机数0-9999+系统当前时间+上传图片名)
        String name = cosFileName + "/" + DateUtils.getNowDate() + random.nextInt(10000) +  substring;
        name = regexName(name);
        //System.out.println("新图片 : " + name);
        try {  
            InputStream inputStream = file.getInputStream();  
            return uploadFile2Cos(inputStream, name);  
        } catch (Exception e) {  
            throw new Exception(e.getMessage());  
        }  
    }  
	
	private static String regexName(String name) {
		Integer [] doc = {1,2,3,4,5,6,7,8,9,0};
		Random random = new Random();
		return name.replace("?",doc[random.nextInt(doc.length)]+"");
	}
	
	
	/**
	 * 删除文件
	 * @param oldHead
	 */
	public static void deleteFile(String fileUrl) {
		if(fileUrl != null){
			COSCredentials cred = new BasicCOSCredentials(CosConstant.SECRETID, CosConstant.SECRETEKEY);
			ClientConfig clientConfig = new ClientConfig(new Region("ap-guangzhou"));
			COSClient cosClient = new COSClient(cred, clientConfig);
			String bucketName = CosConstant.BUCKET;
			
			if(fileUrl.indexOf(CosConstant.URL_PREFIX) != -1){
				String key  = fileUrl.replaceAll(CosConstant.URL_PREFIX,"");
				cosClient.deleteObject(bucketName, key);
			}
		}
	}  
	
//	public static void main(String[] args) throws URISyntaxException, IOException {
////		System.out.println("新地址:"+"C:/pic/dw.jpg");
////		String url = putFile("C:/pic/dw.jpg");
////		System.out.println("新地址:"+url);
//		String fileUrl = "http://game-1256953255.cos.ap-guangzhou.myqcloud.com/imges/201808221650089251188.jpg";
//		System.out.println(fileUrl.replaceAll("http://game-1256953255.cos.ap-guangzhou.myqcloud.com/",""));;
//	}
	
	/** 
     * Description: 判断Cos服务文件上传时文件的contentType 
     * 
     * @param filenameExtension 文件后缀 
     * @return String 
     */  
    public static String getcontentType(String filenameExtension) {  
        if (filenameExtension.equalsIgnoreCase("bmp")) {  
            return "image/bmp";  
        }  
        if (filenameExtension.equalsIgnoreCase("gif")) {  
            return "image/gif";  
        }  
        if (filenameExtension.equalsIgnoreCase("jpeg") || filenameExtension.equalsIgnoreCase("jpg")  
                || filenameExtension.equalsIgnoreCase("png")) {  
            return "image/jpeg";  
        }  
        if (filenameExtension.equalsIgnoreCase("html")) {  
            return "text/html";  
        }  
        if (filenameExtension.equalsIgnoreCase("txt")) {  
            return "text/plain";  
        }  
        if (filenameExtension.equalsIgnoreCase("vsd")) {  
            return "application/vnd.visio";  
        }  
        if (filenameExtension.equalsIgnoreCase("pptx") || filenameExtension.equalsIgnoreCase("ppt")) {  
            return "application/vnd.ms-powerpoint";  
        }  
        if (filenameExtension.equalsIgnoreCase("docx") || filenameExtension.equalsIgnoreCase("doc")) {  
            return "application/msword";  
        }  
        if (filenameExtension.equalsIgnoreCase("xml")) {  
            return "text/xml";  
        }  
        return "image/jpeg";  
    }

	
}
